1076D - Edge Deletion - CodeForces Solution


graphs greedy shortest paths *1800

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
const long long INF = 1e18;
#define pii pair<int, int>
#define pli pair<long long, int>
#define piii pair<int, pair<int, int>>
bool vis[300005];
int n, m, k;
vector<piii> g[300005];
long long dis[300005];
vector<pii> G[300005];
vector<int> ans;
priority_queue<pli, vector<pli>, greater<pli> > q;
void dfs(int x){
	if(ans.size() == k) return ;
	vis[x] = 1;
	for(int i = 0; i < G[x].size(); i++){
		int y = G[x][i].first;
		if(vis[y]) continue;
		if(ans.size() == k) return ;
		ans.push_back(G[x][i].second);
		if(ans.size() == k) return ;
		dfs(y);
	}
}
int main(){
	scanf("%d%d%d", &n, &m, &k);
	for(int i = 1; i <= m; i++){
		int x, y, w;
		scanf("%d%d%d", &x, &y, &w);
		g[x].push_back({y, {w, i}});
		g[y].push_back({x, {w, i}});
	}
	for(int i = 2; i <= n; i++) dis[i] = INF;
	q.push({0, 1});
	while(!q.empty()){
		int u = q.top().second;
		q.pop();
		if(vis[u]) continue;
		vis[u] = 1;
		for(int i = 0; i < g[u].size(); i++){
			int y = g[u][i].first, w = g[u][i].second.first;
			if(dis[y] > dis[u] + w) {
				dis[y] = dis[u] + w;
				q.push({dis[y], y});
			}
		}
	}
	for(int i = 1; i <= n; i++){
		vis[i] = 0;
		for(int j = 0; j < g[i].size(); j++){
			int y = g[i][j].first, w = g[i][j].second.first;
			int id = g[i][j].second.second;
			if(dis[i] + w == dis[y]){
				G[i].push_back({y, id});
			}
		}
	}
	dfs(1);
	cout << ans.size() << endl;
	for(int i = 0; i < ans.size(); i++) {
		cout << ans[i] << " ";
	}
    return 0;
}


Comments

Submit
0 Comments
More Questions

507B - Amr and Pins
379A - New Year Candles
1154A - Restoring Three Numbers
750A - New Year and Hurry
705A - Hulk
492B - Vanya and Lanterns
1374C - Move Brackets
1476A - K-divisible Sum
1333A - Little Artem
432D - Prefixes and Suffixes
486A - Calculating Function
1373B - 01 Game
1187A - Stickers and Toys
313B - Ilya and Queries
579A - Raising Bacteria
723A - The New Year Meeting Friends
302A - Eugeny and Array
1638B - Odd Swap Sort
1370C - Number Game
1206B - Make Product Equal One
131A - cAPS lOCK
1635A - Min Or Sum
474A - Keyboard
1343A - Candies
1343C - Alternating Subsequence
1325A - EhAb AnD gCd
746A - Compote
318A - Even Odds
550B - Preparing Olympiad
939B - Hamster Farm